package com.young.factory;

import com.young.service.CardRiskService;
import com.young.util.CardRiskServiceCodeUtil;
import com.young.util.SpringContextUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.Map;

@Slf4j
public class CardRiskServiceFactory {
    private static Map<String, CardRiskService>cardRiskServiceMap=new ConcurrentReferenceHashMap<>();

    public static CardRiskService getInstance(String bankCode){
        CardRiskService cardRiskService = cardRiskServiceMap.get(bankCode);
        if (cardRiskService==null){
            synchronized (bankCode.intern()){
                if (cardRiskService==null){
                    log.info("重新加载service：{}",CardRiskServiceCodeUtil.getServiceName(bankCode));
                    //双重检查
                    cardRiskService = (CardRiskService) SpringContextUtil.getBean(CardRiskServiceCodeUtil.getServiceName(bankCode));
                    cardRiskServiceMap.put(bankCode,cardRiskService);
                }
            }
        }
        return cardRiskService;
    }

    public static void put(String bankCode,CardRiskService cardRiskService){
        cardRiskServiceMap.put(bankCode,cardRiskService);
    }
}

//@Component
//public class CardRiskServiceFactory {
//    @Autowired
//    private ApplicationContext applicationContext;
//
//    protected Map<String,CardRiskService>cardRiskServiceMap= Maps.newHashMap();
//
//    @PostConstruct
//    public void init(){
//        Map<String, CardRiskService> tempCardRiskServiceMap = applicationContext.getBeansOfType(CardRiskService.class);
//        for (Map.Entry<String,CardRiskService>entry:tempCardRiskServiceMap.entrySet()){
//            CardRiskService cardRiskService = entry.getValue();
//            String cardType = cardRiskService.getCardType();
//            if (Objects.isNull(cardType)) {
//                throw new IllegalArgumentException("错误的CommonHandlerService类型，beanName："+entry.getKey());
//            }
//
//           cardRiskServiceMap.put(cardType,cardRiskService);
//        }
//
//    }
//
//    public CardRiskService getInstance(String cardRiskType){
//        return cardRiskServiceMap.get(cardRiskType);
//    }
//}